<?php

/**
 * 
 * Sorts the files of the dir by name
 * @param dir $dir 		Directory
 * @return dir 			Sorted directory
 */
function sort_dir($dir){
	$i=0;
	while (($element = readdir($dir))!= false){
		$elements[$i]=$element;
		$i++;
	}
	sort($elements);
	return $elements;
}


/**
 * 
 * Prints the header of the file
 * @param file $element
 */
function file_header($element){
	echo "METADATA INFORMATION: <br /> ";
	$file2 = fopen("data/$element", "r");
	for($j=0; $j<2; $j++){
		echo fgets($file2). "<br />";
	}
	fclose($file2);
	echo "<br />";
	echo "--DATE----TIME---PPM--<br/>";
}


/**
 * 
 * Returns the name of the file, before the '.'
 * @param file $file
 * @return string
 */
function get_name($file){
	$elem_name = explode(".",$file);
	$name = $elem_name[0];
	return $name;
}


/**
 * 
 * Returns the extension of the file
 * @param file $file
 * @return string
 */
function get_extension($file){
	$elem_name = explode(".",$file);
	$extension  = $elem_name[1];
	return $extension;
}


/**
 * 
 * Writes the header in recently created file
 * @param file $element		File from we read the header
 * @param file $file		File in which we write the header
 */
function write_header($element, $file){
	fwrite($file, "METADATA INFORMATION:");
	fwrite($file, chr(13).chr(10));
	$file2 = fopen("data/$element", "r");
	for($j=0; $j<2; $j++){
		fwrite($file, fgets($file2));
	}
	fwrite($file, chr(13).chr(10));
	fclose($file2);
	fwrite($file, "--DATE----TIME---PPM--");
	fwrite($file, chr(13).chr(10));
}


/**
 * 
 * Writes the data into a file created for download
 * @param string $line
 */
function show_data($line){
	//The @ character removes the warning messages: 'Cannot modify header information - headers already sent by...'
	@header("Content-type: application/octet-stream");
	@header("Content-Disposition: filename=\"sensordata.dat\"");
	@header("Cache-control: private");
	echo "$line";
}

/**
 * 
 * Return headers from the file
 * @param file $element
 */
function write_headers($element){
	$headers = array();
	$headers[] = "METADATA INFORMATION:";
	$headers[] = chr(13).chr(10);
	$headers[] = chr(13).chr(10);
	$file2 = fopen("data/$element", "r");
	for($j=0; $j<2; $j++){
		$headers[] = fgets($file2);
		if ($j == 1){
			$headers[] = chr(13).chr(10);
		}
	}
	fclose($file2);
	$headers[] = "---DATE------TIME--------------PPM--";
	$headers[] = chr(13).chr(10);
	return $headers;
}
?>